<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:storeProductRule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:storeProductRule:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:storeProductRule:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:storeProductRule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeProductRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="" align="center" prop="id" v-if="true"/>
      <el-table-column label="规格名称" align="center" prop="ruleName"/>
<!--      <el-table-column label="规格值" align="center" prop="ruleValue"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:storeProductRule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:storeProductRule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规则值(规格)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="formDynamic" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="规格名称：" prop="ruleName">
              <el-input maxlength="20" v-model="formDynamic.ruleName" placeholder="请输入标题名称"/>
            </el-form-item>
          </el-col>
          <el-col v-for="(item, index) in formDynamic.ruleValue" :key="index" :span="24" class="noForm">
            <el-form-item>
              <div class="acea-row row-middle"><span class="mr5">{{ item.value }}</span><i class="el-icon-circle-close"
                                                                                           @click="handleRemove(index)"/>
              </div>
              <div class="rulesBox">
                <el-tag
                  v-for="(j, indexn) in item.detail"
                  :key="indexn"
                  closable
                  size="medium"
                  :disable-transitions="false"
                  class="mb5 mr10"
                  @close="handleClose(item.detail,indexn)"
                >
                  {{ j }}
                </el-tag>
                <el-input
                  v-if="item.inputVisible"
                  ref="saveTagInput"
                  v-model="item.detail.attrsVal"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="createAttr(item.detail.attrsVal,index)"
                  @blur="createAttr(item.detail.attrsVal,index)"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ 添加</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-if="isBtn" :span="24" class="mt10" style="padding-left: 0;padding-right: 0;">
            <el-col :span="8">
              <el-form-item label="规格：">
                <el-input v-model="attrsName" placeholder="请输入规格"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格值：">
                <el-input v-model="attrsVal" placeholder="请输入规格值"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" class="mr10" @click="createAttrName">确定</el-button>
              <el-button @click="offAttrName">取消</el-button>
            </el-col>
          </el-col>
          <Spin v-if="spinShow" size="large" fix/>
        </el-row>
        <el-button v-if="!isBtn" type="primary" icon="md-add" class="ml40 mt10" @click="addBtn">添加新规格</el-button>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStoreProductRule,
  getStoreProductRule,
  delStoreProductRule,
  addStoreProductRule,
  updateStoreProductRule
} from "@/api/system/storeProductRule";

export default {
  name: "StoreProductRule",
  data() {
    return {
      sourceAttribute: [
        {
          name: '颜色',
          item: ['黑', '金', '白']
        },
        {
          name: '内存',
          item: ['16G', '32G']
        }
      ],
      attribute: [],
      sku: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规则值(规格)表格数据
      storeProductRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: undefined,
        ruleValue: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // id: [
        //   {required: true, message: "不能为空", trigger: "blur"}
        // ],
        // ruleName: [
        //   {required: true, message: "规格名称不能为空", trigger: "blur"}
        // ],
        // ruleValue: [
        //   {required: true, message: "规格值不能为空", trigger: "blur"}
        // ]
      },
      formDynamic: {
        ruleName: '',
        ruleValue: []
      },
      attrsName: '',
      attrsVal: '',
      isBtn: false,
      results: [],
      result: [],
      spinShow: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 添加按钮
    addBtn() {
      this.isBtn = true
    },
    handleClose(item, index) {
      item.splice(index, 1)
    },
    // 取消
    offAttrName() {
      this.isBtn = false
    },
    /** 查询商品规则值(规格)列表 */
    getList() {
      this.loading = true;
      listStoreProductRule(this.queryParams).then(response => {
        this.storeProductRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 删除
    handleRemove(index) {
      this.formDynamic.ruleValue.splice(index, 1)
    },
    // 添加规则名称
    createAttrName() {
      if (this.attrsName && this.attrsVal) {
        const data = {
          value: this.attrsName,
          detail: [
            this.attrsVal
          ]
        }
        this.formDynamic.ruleValue.push(data)
        const hash = {};
        this.formDynamic.ruleValue = this.formDynamic.ruleValue.reduce(function (item, next) {
          /* eslint-disable */
          hash[next.value] ? '' : hash[next.value] = true && item.push(next);
          return item
        }, [])
        this.attrsName = '';
        this.attrsVal = '';
        this.isBtn = false;
      } else {
        this.$message.warning('请添加规格名称');
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.formDynamic.ruleValue[idx].detail.push(num);
        var hash = {};
        this.formDynamic.ruleValue[idx].detail = this.formDynamic.ruleValue[idx].detail.reduce(function (item, next) {
          /* eslint-disable */
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
        this.formDynamic.ruleValue[idx].inputVisible = false
      } else {
        this.$message.warning('请添加属性');
      }
    },
    showInput(item) {
      this.$set(item, 'inputVisible', true)
    },
    clear() {
      this.$refs['form'].resetFields();
      this.formDynamic.ruleValue = [];
      this.formDynamic.ruleName = ''
      this.isBtn = false;
      this.attrsName = '';
      this.attrsVal = '';
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ruleName: undefined,
        ruleValue: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品规则值(规格)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getStoreProductRule(id).then(response => {
        this.loading = false;
        this.formDynamic = response.data;
        this.formDynamic.ruleValue = JSON.parse(this.formDynamic.ruleValue)
        console.log(this.formDynamic, '2222')
        this.open = true;
        this.title = "修改商品规则值(规格)";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const data = {
        "id": this.formDynamic.id || null,
        "ruleName": this.formDynamic.ruleName,
        "ruleValue": JSON.stringify(this.formDynamic.ruleValue)
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formDynamic.ruleValue.length === 0) {
            return this.$message.warning('请至少添加一条属性规格！');
          }
          this.buttonLoading = true;
          if (this.formDynamic.id != null) {
            updateStoreProductRule(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addStoreProductRule(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }

          this.clear()
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品规则值(规格)编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delStoreProductRule(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/storeProductRule/export', {
        ...this.queryParams
      }, `storeProductRule_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.footer {
  justify-content: flex-end;
}
</style>
